"""
RagFlow 客户端 GUI 查看日志功能模块
"""

import os
import re
import logging
from PySide6.QtWidgets import QMessageBox, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QComboBox, QPushButton
from ragflow_client.gui.features.base_feature import BaseFeature
from ragflow_client.utils.logger import get_logger

logger = get_logger(__name__)


class LogFeature(BaseFeature):
    """查看日志功能类"""
    
    def __init__(self, parent=None):
        """初始化查看日志功能"""
        super().__init__(parent)
        self.log_tab = None
        self.log_level_combo = None
        self.log_filter_text = None
    
    def execute(self):
        """执行查看日志功能"""
        # 创建日志窗口
        content_widget = QWidget()
        layout = QVBoxLayout(content_widget)
        
        # 创建过滤控件
        filter_layout = QHBoxLayout()
        layout.addLayout(filter_layout)
        
        # 日志级别过滤
        filter_layout.addWidget(QLabel("日志级别:"))
        self.log_level_combo = QComboBox()
        self.log_level_combo.addItem("全部", "ALL")
        self.log_level_combo.addItem("调试", "DEBUG")
        self.log_level_combo.addItem("信息", "INFO")
        self.log_level_combo.addItem("警告", "WARNING")
        self.log_level_combo.addItem("错误", "ERROR")
        self.log_level_combo.addItem("严重错误", "CRITICAL")
        self.log_level_combo.currentIndexChanged.connect(self.filter_log)
        filter_layout.addWidget(self.log_level_combo)
        
        # 刷新按钮
        refresh_button = QPushButton("刷新日志")
        refresh_button.clicked.connect(self.refresh_log)
        filter_layout.addWidget(refresh_button)
        
        # 添加弹性空间
        filter_layout.addStretch()
        
        # 创建日志选项卡组件
        from ragflow_client.gui.components.log_tab import LogTabWidget
        self.log_tab = LogTabWidget(self.parent)
        layout.addWidget(self.log_tab)
        
        # 读取日志文件并显示
        self.load_log_file()
        
        # 创建窗口
        self.window = self.create_window("查看日志", content_widget)
        self.window.show()
    
    def refresh_log(self):
        """刷新日志"""
        if self.log_tab:
            self.log_tab.clear_log()
            self.load_log_file()
    
    def filter_log(self):
        """根据选择的日志级别过滤日志"""
        if not self.log_tab:
            return
            
        # 获取选择的日志级别
        level = self.log_level_combo.currentData()
        
        # 重新加载日志
        self.log_tab.clear_log()
        self.load_log_file(level)
    
    def load_log_file(self, level_filter="ALL"):
        """
        读取日志文件并显示
        
        Args:
            level_filter: 日志级别过滤器，默认为"ALL"表示显示所有级别
        """
        if not self.log_tab:
            return
            
        try:
            # 日志文件路径
            log_file = "app.log"
            
            # 检查日志文件是否存在
            if not os.path.exists(log_file):
                self.log_tab.append_log("日志文件不存在: app.log")
                return
            
            # 获取文件大小
            file_size = os.path.getsize(log_file)
            
            # 如果文件太大，只读取最后的部分
            max_size = 1024 * 1024  # 1MB
            
            if file_size > max_size:
                self.log_tab.append_log(f"日志文件较大 ({file_size / 1024 / 1024:.2f} MB)，只显示最后 1MB 内容")
                
                with open(log_file, "rb") as f:
                    f.seek(-max_size, os.SEEK_END)
                    # 跳过第一行，因为可能是不完整的
                    f.readline()
                    # 读取剩余内容
                    log_content = f.read().decode("utf-8", errors="replace")
            else:
                # 读取整个日志文件
                with open(log_file, "r", encoding="utf-8", errors="replace") as f:
                    log_content = f.read()
            
            # 显示日志内容
            if log_content:
                # 如果需要过滤特定级别的日志
                if level_filter != "ALL":
                    filtered_lines = []
                    for line in log_content.splitlines():
                        # 检查行是否包含指定的日志级别
                        if f" - {level_filter} - " in line:
                            filtered_lines.append(line)
                    
                    if filtered_lines:
                        self.log_tab.append_log("\n".join(filtered_lines))
                    else:
                        self.log_tab.append_log(f"没有找到 {level_filter} 级别的日志")
                else:
                    # 显示所有日志
                    self.log_tab.append_log(log_content)
            else:
                self.log_tab.append_log("日志文件为空")
                
        except Exception as e:
            error_msg = f"读取日志文件失败: {str(e)}"
            logger.error(error_msg)
            self.log_tab.append_log(f"错误: {error_msg}")
